package com.liujian.esapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liujian.esapi.entity.PolicyHit;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class PolicyController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @GetMapping("/policy/hit")
    public String policyHit(String keyword) throws IOException {
        SearchRequest request = new SearchRequest("index3");
        //创建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //不分词,精确匹配
//         TermQueryBuilder query = QueryBuilders.termQuery("text", "科技成果");
        //先分词,在匹配
        MatchQueryBuilder query = QueryBuilders.matchQuery("text", keyword);


        HighlightBuilder highlightBuilder = new HighlightBuilder();

        highlightBuilder.field(new HighlightBuilder.Field("id"));
        highlightBuilder.field(new HighlightBuilder.Field("text"));
        highlightBuilder.preTags("<span style='color:red'>").postTags("</span>");
        searchSourceBuilder.query(query);
        searchSourceBuilder.highlighter(highlightBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        request.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits searchHits = response.getHits();
        TotalHits totalHits = searchHits.getTotalHits();
        long value = totalHits.value;

        System.out.println("totalHits value:"+value);
        SearchHit[] hits = searchHits.getHits();
        float maxScore = searchHits.getMaxScore();
//        System.out.println("maxScore value:"+maxScore);
        List<HashMap<String,Object>> hashMapList = new ArrayList<HashMap<String,Object>>();
        for(SearchHit hit : hits) {
            PolicyHit policyHit = JSONObject.parseObject(hit.getSourceAsString(), PolicyHit.class);

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlightFieldText = highlightFields.get("text");
            if (highlightFieldText != null) {
                Text[] fragments = highlightFieldText.fragments();
                String fragmentString = fragments[0].string();
                System.out.println(fragmentString);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put(policyHit.getId() + "", fragmentString);
                hashMapList.add(map);
            }


        }
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(hashMapList));
        return jsonArray.toJSONString();

    }
}
